How to do the fast execution of the JavaScript code in a server? What things we need to keep in mind before deploying my code in a server?
How to speed up the website with my JavaScript code in the server?
39720-Jul-2021
Updated on 20-Jul-2021
Anonymous User
04-Aug-2021Fast execution of JavaScript should be important for the developers as well as the for the user. So the things we should keep in mind before writing JavaScript code are as follows:
1.) Reduce Activity in Loops
Loops are the basics which are used in programming. So before each statement in a loop, including the for statement, is executed for each iteration of the loop.
Statements or assignments that can be placed outside the loop will make the loop run faster.
Bad way to write code :
Better way to write above code:
2.)Reduce DOM Access
Accessing HTML DOM is very slow compared to other JavaScript statements.
If you expect to access a DOM element multiple times, access it once, and use it as a local variable:
3.) Reduce DOM Size
The number of HTML elements should be minimal without any requirement:
This will always improve page loading, and speed up rendering (page display), especially on smaller devices.
Every attempt to search the DOM (such as getElementsByTagName) would benefit from a smaller DOM.
4.) Avoid Unnecessary Variables
Do not create a unnecessary variables if you don't need it in the document
Often you can replace code like this:
With this:
5.) Delay JavaScript Loading
Placing your script at the bottom of the page body allows the browser to load the page first.
While one script is being downloaded, the browser will not initiate any other downloads. Also all parsing and rendering activity can be blocked.
The HTTP specification defines that browsers should not download more than two components in parallel.One option is to use defer='true' in the script tag. The defer attribute specifies that the script should be executed after the page is parsed, but this only works for external scripts.
If possible, you can add your script after the page is loaded:
Example
Hope this information will be helpful for you in enhancing the performance of your JavaScript code.
Happy Coding!